const workerDate = new Worker('../script/worker-date.js');
const workerHandler = {
    loadMonthDay,
};
workerDate.onmessage = function (e) {
    const result = JSON.parse(e.data);
    const f = workerHandler[result.handle];
    if (f) {
        f(result);
    }
    else {
        console.error(`没有对应'${result.handle}'的处理函数`);
    }
};

const FACILITY = {
    '0': {'name': '微波炉', 'style': 'icon-weibolu', 'id': 0},
    '5': {'name': '淋浴', 'style': 'icon-linyu', 'id': 5},
    '6': {'name': '牙具', 'style': 'icon-yaju', 'id': 6},
    '7': {'name': '香皂', 'style': 'icon-xiangzao', 'id': 7},
    '8': {'name': '拖鞋', 'style': 'icon-tuoxie', 'id': 8},
    '9': {'name': '手纸', 'style': 'icon-shouzhi', 'id': 9},
    '10': {'name': '毛巾', 'style': 'icon-maojin', 'id': 10},
    '11': {'name': '沐浴露', 'style': 'icon-muyulu', 'id': 11},
    '12': {'name': '浴缸', 'style': 'icon-yugang', 'id': 12},
    '13': {'name': '电视', 'style': 'icon-dianshi', 'id': 13},
    '14': {'name': '空调', 'style': 'icon-kongtiao', 'id': 14},
    '15': {'name': '饮水机', 'style': 'icon-yinshuiji', 'id': 15},
    '16': {'name': '冰箱', 'style': 'icon-bingxiang', 'id': 16},
    '17': {'name': '洗衣机', 'style': 'icon-xiyiji', 'id': 17},
    '18': {'name': '无线网络', 'style': 'icon-wuxianwangluo', 'id': 18},
    '19': {'name': '有线网络', 'style': 'icon-youxianwangluo', 'id': 19},
    '20': {'name': '暖气', 'style': 'icon-nuanqi', 'id': 20},
    '21': {'name': '电梯', 'style': 'icon-dianti', 'id': 21},
    '22': {'name': '停车位', 'style': 'icon-tingchewei', 'id': 22},
    '23': {'name': '门禁系统', 'style': 'icon-menjinxitong', 'id': 23},
    '24': {'name': '允许吸烟', 'style': 'icon-webiconyunxuxiyan', 'id': 24},
    '25': {'name': '允许做饭', 'style': 'icon-webiconyunxuzuofan', 'id': 25},
    '26': {'name': '可带宠物', 'style': 'icon-ichongwu', 'id': 26},
    '27': {'name': '允许聚会', 'style': 'icon-juhuihongpa', 'id': 27},
    '28': {'name': '24小时热水', 'style': 'icon-xiaoshireshui', 'id': 28},
    '34': {'name': '接送机', 'style': 'icon-jiesongji', 'id': 34},
    '35': {'name': '导游 ', 'style': 'icon-daoyou', 'id': 35},
};

const pubData = {
    trigon: { // 控制 日期,位置,排序 popup的显示
        't1': false,
        't2': false,
        't3': false,
    },
};
// noinspection JSUnusedGlobalSymbols
const vm = new Vue({
    el: '#main',
    data: {
        houseList: [], // 房源列表
        cityId: '',
        filtrateBoxShow: false, // 筛选侧栏的显示
        trigon: pubData.trigon,
        selectedSort: 1, // 选择的排序规则
        selectedDate: { // 用户选择的日期
            start: null,
            end: null,
        },
        dateList: [], // 日期二维列表
        dateLinearList: [], // 日期线性表
        screenData: { // 筛选的数据
            position: [],
            filter: [],
        },
        selectedScreenItem: '', // 用户选择的位置
        selectedFilter: { // 用户的筛选
            rentType: '',
            price: {
                s: '',
                e: '',
            },
            houseType: '',
            facility: {},
            peopleNum: 0,
        },
        filterItemShow: {
            '0': false,
            '1': false,
        },
        finishType: '',
        pageNum: 1,
        reqHouseListSync: true,
        searchText: '',
    },
    methods: {
        // 用户选择位置
        selectScreenItem(item) {
            if (this.selectedScreenItem) {
                this.selectedScreenItem.selected = false;
            }
            this.selectedScreenItem = item;
            item.selected = true;
            vmMenu.menuTxt.position = item.name;
            closeAllPopup();
            finish(2);
        },
        changePeopleNum(num) {
            let n = this.selectedFilter.peopleNum;
            n += num;
            if (n < 0) {
                return;
            }
            this.selectedFilter.peopleNum = n;
            setBubbleStyle();
        },
        resetFilterItem,
        collectHouse,
        selectDay,
        clickHouseEvent,
        selectSort,
        toggleFilterItemShow,
        selectFilterItem,
        toggleScreenTermShow,
    },
});

// noinspection JSUnusedGlobalSymbols
const vmMenu = new Vue({
    el: '#filter-menu',
    data: {
        trigon: pubData.trigon,
        menuTxt: {
            date: '',
            position: '位置',
            sort: '排序',
            filtrate: 0,
        },
    },
    methods: {
        toggleTrigonStyle,
    },
});

async function apiready() {
    const close = fxj.dialog.loading();
    const result = await ajax({
        url: 'home/search/search',
        type: 'POST',
        data: {
            code: localStorage.getItem('cityId'),
            search: decodeURI(fxj.getSearch().get('search')),
            type: 1,
        },
    });
    if (result.err !== 0) {
        toast(result.msg);
    }
    else {
        forEach(result.data, (o) => {
            o.img = fxj.fixImgUrl(o.img);
        });
        vm.houseList = result.data;
    }
    close();
}

!function main() {
    fxj.fixStatusBar('.fxj-header');
    fixLayout();
    getSearchHouseList();
    getDateList();
    reqPositionScreenData();
    reqScreen();
    loadMore();
}();

async function loadMore() {
    isToBottom(100, (ok, el) => {
        if (!ok) return;
        if (vm.reqHouseListSync) {
            finish(vm.finishType, false);
            vm.reqHouseListSync = false;
        }
    }, 150);
}


function getDateList() {
    workerDate.postMessage('loadMonthDay');
}

function fixLayout() {
    const header = document.querySelector('.fxj-header');
    const menu = document.getElementById('filter-menu');
    const main = document.getElementById('main');
    menu.style.top = header.offsetHeight + 'px';
    main.style.marginTop = menu.offsetHeight + header.offsetHeight + 'px';
    forEach(document.querySelectorAll('.side-container'), side => {
        side.style.paddingTop = menu.offsetHeight + header.offsetHeight + 'px';
    });
}

function clickHouseEvent(evt, house) {
    goPage(`house_res_detail.html?id=${house.id}`);
}

// 根据用户的输入请求房源列表
function getSearchHouseList() {
    let cityId = localStorage.getItem('cityId');
    const input = document.getElementById('searchStr');
    input.addEventListener('keyup', (e) => {
        if (e.keyCode === 13) {
            vm.searchText = input.value;
            getHouseList(cityId, input.value);
        }
    });
}

function clickSearchHouseList() {
    let cityId = localStorage.getItem('cityId');
    const input = document.getElementById('searchStr');
    vm.searchText = input.value;
    getHouseList(cityId, vm.searchText);
}

async function getHouseList(cityId, value) {
    const close = fxj.dialog.loading({
        noBg: true,
    });
    const result = await ajax({
        url: 'home/search/search',
        type: 'POST',
        data: {
            code: cityId,
            search: value,
            type: 1,
        },
    });
    close();
    if (result.err !== 0) {
        mui.toast(result.msg);
        return;
    }
    forEach(result.data, (house) => {
        house.img = fxj.fixImgUrl(house.img);
    });
    vm.houseList = result.data;
}

// 日期,位置,排序 按钮以及popup的控制
function toggleTrigonStyle(i) {
    let map = new Set([1, 2, 3]);
    if (vmMenu.menuTxt.sort === '排序' && i === 3) {
        openedSortPopup();
    }
    if (i === 4) {
        for (let idx of map) {
            vmMenu.trigon[`t${idx}`] = false;
        }
        vm.filtrateBoxShow = true;
    }
    else {
        map.delete(i);
        vmMenu.trigon[`t${i}`] = !vmMenu.trigon[`t${i}`];
        for (let idx of map) {
            vmMenu.trigon[`t${idx}`] = false;
        }
    }
}

function closeAllPopup() {
    vmMenu.trigon.t1 = false;
    vmMenu.trigon.t2 = false;
    vmMenu.trigon.t3 = false;
    closeSideFiltrate();
}

function closeSideFiltrate() {
    vm.filtrateBoxShow = false;
}

function selectSort(i) {
    vm.selectedSort = i;
    openedSortPopup(i);
    closeAllPopup();
    finish(-1);
}

// 用户选择排序方式
function openedSortPopup() {
    vmMenu.menuTxt.sort = '默认排序';
    const txtMap = new Map([
        [1, '默认排序'],
        [2, '销量优先'],
        [3, '好评优先'],
        [4, '高价优先'],
        [5, '低价优先'],
    ]);
    openedSortPopup = function (i) {
        vmMenu.menuTxt.sort = txtMap.get(i);
    };
}

function loadMonthDay(res) {
    if (res.ok) {
        vm.dateList = res.data;
        for (let v of res.data) {
            vm.dateLinearList = vm.dateLinearList.concat(v.dayList);
        }
    }
}

// 用户选择日期,选择两天,自动求范围,否则重置
function selectDay(i) {
    if (!isExist(vm.selectedDate.start) && vm.selectedDate.start !== i) {
        vm.selectedDate.start = i;
        vm.dateLinearList[i].selected = true;
    }
    else if (!isExist(vm.selectedDate.end)) {
        vm.selectedDate.end = i;
        vm.dateLinearList[i].selected = true;
        setSelectedDayRange(true);
        const [s, e] = getStartIndexAndEndIndex();
        const sDay = vm.dateLinearList[s];
        const eDay = vm.dateLinearList[e];
        vmMenu.menuTxt.date = `${sDay.month}.${sDay.day}-${eDay.month}.${eDay.day}`;
        closeAllPopup();
        finish(1);
    }
    else {
        setSelectedDayRange(false);
    }
}

function getStartIndexAndEndIndex() {
    const s = vm.selectedDate.start;
    const e = vm.selectedDate.end;
    return s > e ? [e, s] : [s, e];
}

function setSelectedDayRange(selected) {
    let [s, e] = getStartIndexAndEndIndex();
    if (!selected) {
        vm.selectedDate.start = null;
        vm.selectedDate.end = null;
        vmMenu.menuTxt.date = '日期';
    }
    while (s++ <= e) {
        if (vm.dateLinearList[s]) {
            vm.dateLinearList[s].selected = selected;
        }
    }
}

function clearAllSelectedDate(i) {
    if (i === 1) {
        vm.selectedDate.start = null;
        vm.selectedDate.end = null;
        vmMenu.menuTxt.date = '';
        forEach(vm.dateLinearList, day => {
            if (day && day.selected) {
                day.selected = false;
            }
        });
    }
    else if (i === 2) {
        vmMenu.menuTxt.position = '位置';
        if (vm.selectedScreenItem) {
            vm.selectedScreenItem.selected = false;
            vm.selectedScreenItem = null;
        }
    }
    closeAllPopup();
    finish(i);
}

function setBubbleStyle() {
    let n = 0;
    vm.selectedFilter.rentType !== '' && n++;
    vm.selectedFilter.houseType !== '' && n++;
    (vm.selectedFilter.price.s !== '' || vm.selectedFilter.price.e !== '') && n++;
    vm.selectedFilter.peopleNum !== 0 && n++;
    Object.keys(vm.selectedFilter.facility).length > 0 && n++;
    vmMenu.menuTxt.filtrate = n;
}

async function finish(i, re = true) {
    const close = fxj.dialog.loading({
        noBg: true,
    });
    if (re) {
        vm.pageNum = 1;
    }
    else {
        vm.pageNum += 1;
    }
    vm.finishType = i;
    const filter = vm.selectedFilter; // 筛选框框里的筛选条件
    const reqData = {
        pageNum: vm.pageNum,
        type: 2, // 表明是通过条件筛选
        code: localStorage.getItem('cityId'),
        sort: 1, // 1 为默认排序
        rent_type: filter.rentType,
        room_price: [filter.price.s, filter.price.e],
        room_capacity: filter.houseType,
        room_location: {},
        rent_facility: (() => { // 筛选的设施
            let t = [];
            forEach(Object.keys(filter.facility), k => {
                t.push(Number(filter.facility[k].id));
            });
            return t;
        })(),
        counter: filter.peopleNum > 10 ? 10 : filter.peopleNum, // 入住人大于10人则传10
        search: vm.searchText,
    };
    const endDayIndex = vm.selectedDate.end; // 选择日期的结束日期
    if (endDayIndex) {
        const startDay = vm.dateLinearList[vm.selectedDate.start];
        const endDay = vm.dateLinearList[endDayIndex];
        reqData.search_time = {
            start: `${startDay.year}/${startDay.month}/${startDay.day}`,
            end: `${endDay.year}/${endDay.month}/${endDay.day}`,
        };
    }
    const position = vm.selectedScreenItem; // 筛选的位置
    if (position) {
        reqData.room_location.is_district = position.pid === '1' ? 1 : -1;
        if (reqData.room_location.is_district === 1) {
            reqData.room_location.district_code = position.value;
        }
        else {
            let [lng, lat] = position.value.split('&');
            reqData.room_location.lng = lng;
            reqData.room_location.lat = lat;
        }
    }
    switch (vm.selectedSort) {
        case 1:
            reqData.latest = 1;
            break;
        case 2:
            reqData.amount = 1;
            break;
        case 3:
            reqData.comment = 1;
            break;
        case 4:
            reqData.price = 1;
            break;
        case 5:
            reqData.price = 0;
            break;
    }
    if (i === 4) {
        vm.filtrateBoxShow = false;
    }
    else if (i !== -1) {
        vm.trigon[`t${i}`] = false;
    }
    const res = await ajax({
        url: 'home/search/search',
        data: reqData,
    });
    close();
    vm.reqHouseListSync = true;
    if (res.err !== 0) {
        toast(res.msg);
        return;
    }
    if (res.data.length < 1) {

    }
    else {
        forEach(res.data, house => {
            house.img = fxj.fixImgUrl(house.img);
        });
        if (re) {
            vm.houseList = res.data;
        }
        else {
            vm.houseList = vm.houseList.concat(res.data);
        }
    }
}

async function reqPositionScreenData() {
    const res = await ajax({
        url: 'home/search/getCondition',
        data: {
            cityId: localStorage.getItem('cityId'),
        },
    });
    if (!res.msg) {
        return;
    }
    forEach(res.msg, (term) => {
        term.show = false;
        forEach(term.list, (item) => {
            item.selected = false;
        });
    });
    vm.screenData.position = res.msg;
}

function toggleScreenTermShow(term) {
    term.show = !term.show;
}

async function reqScreen() {
    const res = await ajax({
        url: 'home/search/getFacility',
        data: {
            cityId: localStorage.getItem('cityId'),
        },
    });
    let idList = [];
    forEach(res.msg, item => {
        idList.push(item.id);
    });
    let tempList = [];
    forEach(idList, id => {
        if (!!FACILITY[id]) {
            tempList.push({
                id,
                name: FACILITY[id].name,
                style: FACILITY[id].style,
                selected: false,
            });
        }
    });
    vm.screenData.filter = tempList;
}

function toggleFilterItemShow(i) {
    vm.filterItemShow[i] = !vm.filterItemShow[i];
}

function selectFilterItem(type, item, multi) {
    if (multi) {
        if (item.selected) {
            item.selected = false;
            delete vm.selectedFilter[type][item.name];
        }
        else {
            item.selected = true;
            vm.selectedFilter[type][item.name] = item;
        }
    }
    else {
        vm.selectedFilter[type] = item;
    }
    setBubbleStyle();
}

function resetFilterItem() {
    vm.selectedFilter.rentType = '';
    vm.selectedFilter.houseType = '';
    vm.selectedFilter.price.s = '';
    vm.selectedFilter.price.e = '';
    vm.selectedFilter.peopleNum = 0;
    forEach(Object.keys(vm.selectedFilter.facility), k => {
        vm.selectedFilter.facility[k].selected = false;
        delete vm.selectedFilter.facility[k];
    });
    setBubbleStyle();
    closeAllPopup();
    finish(4);
}

function collectHouse(house) {
    if (house.is_collect === 1) {
        house.is_collect = 0;
    }
    else {
        house.is_collect = 1;
    }
    fxj.api.collectHouse(house.id);
}
